<template>
  <div class="ai-assistant-app">
    <!-- Sidebar Navigation -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h2>AI 助手</h2>
      </div>
      <el-button type="primary" class="new-chat-btn" @click="startNewChat">
        <el-icon><Plus /></el-icon>
        <span>开启新对话</span>
      </el-button>
      <!-- 对话列表 -->
      <div class="conversation-list" v-if="conversationList.length > 0">
        <div class="conversation-items">
          <div v-for="group in groupedConversations" :key="group.title" class="conversation-group">
            <div class="group-title" v-if="group.title">{{ group.title }}</div>
            <div
              v-for="conv in group.conversations"
              :key="conv.id"
              :class="['conversation-item', { active: conv.id === currentConversationId }]"
              @click="switchConversation(conv.id)"
            >
              <div class="conversation-content">
                <div class="conversation-id-display">
                  <span class="id-label">ID:</span>
                  <span class="id-value">{{ conv.id }}</span>
                </div>
              </div>
              <div class="conversation-actions" @click.stop>
                <el-dropdown trigger="click" placement="bottom-start" :offset="5">
                  <el-icon class="more-icon"><MoreFilled /></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>
                        <el-icon><EditPen /></el-icon>
                        <span>重命名</span>
                      </el-dropdown-item>
                      <el-dropdown-item
                        class="delete-item"
                        @click="handleDeleteConversation(conv.id)"
                      >
                        <el-icon><Delete /></el-icon>
                        <span>删除</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <div class="chat-container" :class="{ 'has-messages': chatHistory.length > 0 }">
        <div class="chat-content" :class="{ 'has-messages': chatHistory.length > 0 }">
          <!-- 当没有消息时显示欢迎界面 -->
          <template v-if="chatHistory.length === 0 && !loadingHistory">
            <!-- 欢迎消息 -->
            <div class="welcome-message">
              <h2 class="welcome-title">我是 AI助手，很高兴见到你！</h2>
              <p class="welcome-subtitle">
                我可以帮你写代码、读文件、写作各种创意内容，请把你的任务交给我吧~
              </p>
            </div>

            <!-- 输入框区域 -->
            <div class="input-wrapper">
              <el-input
                v-model="message"
                type="textarea"
                placeholder="给 DeepSeek 发送消息"
                :autosize="{ minRows: 1, maxRows: 8 }"
                resize="none"
                class="message-input"
                @keydown.enter.exact.prevent="sendMessage"
                @keydown.enter.shift.exact="handleNewLine"
              />
              <div class="input-actions">
                <el-tooltip content="上传文件" placement="top">
                  <el-button class="attach-btn" circle size="default">
                    <el-icon><Paperclip /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-button
                  type="primary"
                  :disabled="!message.trim()"
                  @click="sendMessage"
                  class="send-btn"
                  circle
                  size="default"
                >
                  <el-icon><Top /></el-icon>
                </el-button>
              </div>
            </div>
          </template>

          <!-- 当有消息时显示对话界面 -->
          <template v-else>
            <!-- 加载聊天历史提示 -->
            <div class="loading-history" v-if="loadingHistory">
              <div class="loading-content">
                <div class="loading-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <span class="loading-text">正在加载聊天记录...</span>
              </div>
            </div>

            <!-- 聊天历史 -->
            <div class="chat-history" v-else>
              <div v-for="(msg, idx) in chatHistory" :key="idx" :class="['msg-row', msg.role]">
                <div class="msg-avatar">
                  <img
                    :src="msg.role === 'assistant' ? '/ai.png' : '/user.png'"
                    alt="头像"
                    class="avatar"
                  />
                </div>
                <div class="msg-content-wrapper">
                  <div class="msg-content" :class="msg.role">
                    <div v-if="msg.isLoading" class="loading-content">
                      <div class="loading-dots">
                        <span></span>
                        <span></span>
                        <span></span>
                      </div>
                      <span class="loading-text">AI正在思考中...</span>
                    </div>
                    <pre v-else>{{ msg.content }}</pre>
                  </div>
                </div>
              </div>
            </div>

            <!-- 固定在底部的输入框 -->
            <div class="input-container-fixed">
              <div class="input-wrapper">
                <el-input
                  v-model="message"
                  type="textarea"
                  placeholder="给 DeepSeek 发送消息"
                  :autosize="{ minRows: 1, maxRows: 8 }"
                  resize="none"
                  class="message-input"
                  @keydown.enter.exact.prevent="sendMessage"
                  @keydown.enter.shift.exact="handleNewLine"
                />
                <div class="input-actions">
                  <el-tooltip content="上传文件" placement="top">
                    <el-button class="attach-btn" circle size="default">
                      <el-icon><Paperclip /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-button
                    type="primary"
                    :disabled="!message.trim() || loading"
                    @click="sendMessage"
                    class="send-btn"
                    circle
                    size="default"
                  >
                    <el-icon><Top /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>

    <!-- 全局底部提示 -->
    <div class="global-footer">
      <span class="global-hint">内容由 AI 生成，请仔细甄别</span>
    </div>
  </div>
</template>

<script setup>
import {
  chatWithAIStream,
  getConversationIds,
  getChatHistory,
  deleteConversation,
} from './api/index'
import { ref, nextTick, onMounted, computed } from 'vue'
import { Plus, Top, Paperclip, MoreFilled, EditPen, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const message = ref('')
const chatHistory = ref([]) // 聊天记录
const loading = ref(false) // 加载状态
const loadingHistory = ref(false) // 加载聊天历史状态
const currentEventSource = ref(null) // 当前的 EventSource 连接
const currentConversationId = ref('') // 当前对话ID
const conversationList = ref([]) // 对话列表

// 时间分组的计算属性
const groupedConversations = computed(() => {
  const groups = {
    today: { title: '今天', conversations: [] },
    yesterday: { title: '昨天', conversations: [] },
    week: { title: '7天内', conversations: [] },
    month: { title: '30天内', conversations: [] },
    older: { title: '', conversations: [] },
  }

  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
  const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
  const monthAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)

  conversationList.value.forEach((conv) => {
    const convDate = new Date(parseInt(conv.id))
    const convDay = new Date(convDate.getFullYear(), convDate.getMonth(), convDate.getDate())

    if (convDay.getTime() === today.getTime()) {
      groups.today.conversations.push(conv)
    } else if (convDay.getTime() === yesterday.getTime()) {
      groups.yesterday.conversations.push(conv)
    } else if (convDate >= weekAgo) {
      groups.week.conversations.push(conv)
    } else if (convDate >= monthAgo) {
      groups.month.conversations.push(conv)
    } else {
      const yearMonth =
        convDate.getFullYear() + '-' + String(convDate.getMonth() + 1).padStart(2, '0')
      let olderGroup = groups.older.conversations.find((g) => g.title === yearMonth)
      if (!olderGroup) {
        olderGroup = { title: yearMonth, conversations: [] }
        groups.older.conversations.push(olderGroup)
      }
      olderGroup.conversations.push(conv)
    }
  })

  // 对旧的对话按年月倒序排列
  groups.older.conversations.sort((a, b) => b.title.localeCompare(a.title))

  return [
    groups.today,
    groups.yesterday,
    groups.week,
    groups.month,
    ...groups.older.conversations,
  ].filter((group) => group.conversations.length > 0)
})

// 生成时间戳对话ID
const generateConversationId = () => {
  return Date.now().toString()
}

// 加载对话ID列表
const loadConversationIds = async () => {
  try {
    const ids = await getConversationIds()
    // 将字符串ID转换为对话对象，并按时间倒序排列
    conversationList.value = ids
      .map((id) => ({
        id: id,
        createdAt: new Date(parseInt(id)),
      }))
      .sort((a, b) => b.createdAt - a.createdAt) // 最新的在前面
  } catch (error) {
    console.error('加载对话ID列表失败:', error)
  }
}

// 组件挂载时加载对话ID列表
onMounted(() => {
  loadConversationIds()
})

const startNewChat = () => {
  // 如果有正在进行的连接，先关闭它
  if (currentEventSource.value) {
    currentEventSource.value.close()
    currentEventSource.value = null
  }
  chatHistory.value = []
  message.value = ''
  loading.value = false
  currentConversationId.value = '' // 重置当前对话ID，但不清空对话列表
}

// 处理换行
const handleNewLine = () => {
  message.value += '\n'
}

const sendMessage = async () => {
  if (!message.value.trim() || loading.value) return

  // 如果还没有对话ID，生成一个
  if (!currentConversationId.value) {
    currentConversationId.value = generateConversationId()

    // 检查是否已经存在于列表中，避免重复添加
    const existingConv = conversationList.value.find(
      (conv) => conv.id === currentConversationId.value,
    )
    if (!existingConv) {
      // 添加到对话列表的最前面
      conversationList.value.unshift({
        id: currentConversationId.value,
        createdAt: new Date(),
      })
    }
  }

  const userMsg = message.value
  chatHistory.value.push({ role: 'user', content: userMsg })
  message.value = ''
  loading.value = true

  // 添加一个 loading 消息
  chatHistory.value.push({ role: 'assistant', content: '', isLoading: true })

  await nextTick()
  scrollToBottom()

  let aiMsg = ''
  let hasReceivedData = false
  let scrollTimeout = null

  try {
    currentEventSource.value = chatWithAIStream(
      userMsg,
      currentConversationId.value, // 传递对话ID
      (chunk) => {
        if (!hasReceivedData) {
          hasReceivedData = true
          // 移除 loading 状态，开始显示实际内容
          chatHistory.value[chatHistory.value.length - 1].isLoading = false
        }
        aiMsg += chunk
        // 实时更新最后一条 assistant 消息
        chatHistory.value[chatHistory.value.length - 1].content = aiMsg

        // 使用防抖机制避免过于频繁的滚动
        if (scrollTimeout) {
          clearTimeout(scrollTimeout)
        }
        scrollTimeout = setTimeout(() => {
          scrollToBottom(false) // 使用非平滑滚动，保证跟上实时内容
        }, 50) // 50ms 防抖延迟
      },
      (error) => {
        console.error('Stream error:', error)
        if (!hasReceivedData) {
          chatHistory.value[chatHistory.value.length - 1] = {
            role: 'assistant',
            content: 'AI回复失败，请稍后重试。',
            isLoading: false,
          }
        }
        loading.value = false
        currentEventSource.value = null
        // 清理防抖定时器并执行最后的滚动
        if (scrollTimeout) {
          clearTimeout(scrollTimeout)
        }
        scrollToBottom(true) // 流结束时使用平滑滚动
      },
      () => {
        // 流结束回调
        loading.value = false
        currentEventSource.value = null
        if (!hasReceivedData) {
          chatHistory.value[chatHistory.value.length - 1] = {
            role: 'assistant',
            content: 'AI回复失败，请稍后重试。',
            isLoading: false,
          }
        }
        // 清理防抖定时器并执行最后的滚动
        if (scrollTimeout) {
          clearTimeout(scrollTimeout)
        }
        scrollToBottom(true) // 流结束时使用平滑滚动
      },
    )
  } catch (error) {
    console.error('Failed to start stream:', error)
    chatHistory.value[chatHistory.value.length - 1] = {
      role: 'assistant',
      content: 'AI回复失败，请稍后重试。',
      isLoading: false,
    }
    loading.value = false
    currentEventSource.value = null
    // 清理防抖定时器
    if (scrollTimeout) {
      clearTimeout(scrollTimeout)
    }
    scrollToBottom(true)
  }
}

const scrollToBottom = (smooth = true) => {
  // 使用 requestAnimationFrame 确保DOM更新完成后再滚动
  requestAnimationFrame(() => {
    // 优先使用 chat-container，它是可滚动的容器
    const chatContainer = document.querySelector('.chat-container')
    if (chatContainer) {
      if (smooth && 'scrollTo' in chatContainer) {
        // 使用 smooth 滚动效果
        chatContainer.scrollTo({
          top: chatContainer.scrollHeight,
          behavior: 'smooth',
        })
      } else {
        // 立即滚动到底部（兼容性更好）
        chatContainer.scrollTop = chatContainer.scrollHeight
      }
    }
  })
}

// 切换对话
const switchConversation = async (conversationId) => {
  // 如果有正在进行的连接，先关闭它
  if (currentEventSource.value) {
    currentEventSource.value.close()
    currentEventSource.value = null
  }

  currentConversationId.value = conversationId

  // 清空当前聊天记录
  chatHistory.value = []
  message.value = ''
  loading.value = false
  loadingHistory.value = true

  // 加载该对话的聊天历史
  try {
    const history = await getChatHistory(conversationId)
    // 将后端返回的消息历史转换为前端格式
    chatHistory.value = history.map((msg) => ({
      role: msg.role,
      content: msg.content,
      isLoading: false,
    }))

    // 确保DOM完全更新后再滚动到底部
    await nextTick()
    // 对于长对话历史，滚动到底部查看最新消息
    setTimeout(() => {
      scrollToBottom(false) // 使用非平滑滚动快速到达底部
    }, 150) // 增加延迟确保渲染完成
  } catch (error) {
    console.error('加载聊天历史失败:', error)
    // 可以在这里添加错误提示
  } finally {
    loadingHistory.value = false
    // 确保在加载状态结束后再次尝试滚动
    await nextTick()
    setTimeout(() => {
      scrollToBottom(false) // 确保能滚动到最新消息
    }, 100)
  }
}

// 删除对话
const handleDeleteConversation = async (conversationId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？删除后无法恢复。', '删除对话', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 调用删除API
    await deleteConversation(conversationId)

    // 从本地列表中移除
    conversationList.value = conversationList.value.filter((conv) => conv.id !== conversationId)

    // 如果删除的是当前对话，切换到新对话状态
    if (currentConversationId.value === conversationId) {
      chatHistory.value = []
      currentConversationId.value = ''
      message.value = ''
      loading.value = false
    }

    ElMessage.success('对话删除成功')
  } catch (error) {
    if (error === 'cancel') {
      return // 用户取消删除
    }
    console.error('删除对话失败:', error)
    ElMessage.error('删除对话失败')
  }
}
</script>

<style scoped>
.ai-assistant-app {
  display: flex;
  height: 100vh;
  background-color: #f5f7fa;
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans',
    'Helvetica Neue', sans-serif;
  overflow: hidden;
  padding-bottom: 0; /* 移除padding，因为footer现在只在右侧区域 */
  box-sizing: border-box;
}

.sidebar {
  width: 260px;
  background-color: #f9fbff;
  border-right: 1px solid #e5e5e6;
  padding: 20px 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.sidebar-header {
  width: 100%;
  padding: 10px 20px;
  margin-bottom: 20px;
  text-align: left;
}

.sidebar-header h2 {
  font-size: 18px;
  color: #333;
  font-weight: 600;
}

.new-chat-btn {
  width: calc(100% - 40px);
  margin: 0 20px 20px;
  border-radius: 8px;
  height: 44px;
  background: #f0f8ff;
  color: #333;
  font-weight: 500;
  border: 1px solid #e5e5e6;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.new-chat-btn:hover {
  background: #e6f3ff;
}

.new-chat-btn span {
  color: #5b9bd5;
  font-weight: 500;
  margin-left: 8px;
}

.new-chat-btn .el-icon {
  color: #5b9bd5;
}

.conversation-list {
  flex: 1;
  margin: 0 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.conversation-items {
  flex: 1;
  overflow-y: auto;
  padding-right: 4px;
}

.conversation-items::-webkit-scrollbar {
  width: 4px;
}

.conversation-items::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.conversation-items::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.conversation-items::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.conversation-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  background-color: #fafbff;
  border-radius: 8px;
  border: 1px solid #e8f0ff;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.conversation-item:hover {
  background-color: #f0f8ff;
  border-color: #d0e5ff;
}

.conversation-item:hover .more-icon {
  opacity: 1;
  width: 24px;
}

.conversation-item.active {
  background-color: #e6f3ff;
  border-color: #5b9bd5;
}

.conversation-group {
  margin-bottom: 16px;
}

.group-title {
  font-size: 13px;
  color: #666;
  font-weight: 600;
  padding: 8px 12px 8px 0;
  margin-bottom: 8px;
  border-bottom: 1px solid #e8f0ff;
}

.conversation-content {
  flex: 1;
  min-width: 0;
}

.conversation-id-display {
  display: flex;
  align-items: center;
  gap: 4px;
}

.id-label {
  font-size: 11px;
  color: #666;
  font-weight: 500;
}

.id-value {
  font-size: 12px;
  color: #5b9bd5;
  font-family: 'Courier New', monospace;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-actions {
  display: flex;
  align-items: center;
  margin-left: 8px;
}

.more-icon {
  font-size: 18px;
  color: #666;
  opacity: 0;
  transition: opacity 0.2s;
  cursor: pointer;
  padding: 6px;
  border-radius: 4px;
}

.more-icon:hover {
  background-color: #f0f0f0;
  color: #333;
}

.delete-item {
  color: #f56c6c !important;
}

.delete-item .el-icon,
.delete-item span {
  color: #f56c6c !important;
}

.delete-item:hover {
  background-color: #fef0f0 !important;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  min-width: 100px;
  font-size: 14px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  font-size: 14px;
  flex-shrink: 0;
}

:deep(.el-dropdown-menu__item span) {
  font-size: 14px;
  flex: 1;
}

:deep(.el-dropdown-menu) {
  min-width: 100px;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e5e6;
  padding: 4px 0;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: #f5f7fa;
}

:deep(.el-dropdown-menu__item:first-child) {
  margin-top: 0;
}

:deep(.el-dropdown-menu__item:last-child) {
  margin-bottom: 0;
}

.main-content {
  flex: 1;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: stretch; /* 改为 stretch，让容器填满高度 */
  padding: 0;
  overflow: hidden;
  height: 100%;
}

.chat-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center; /* 默认居中，有消息时通过类改变 */
  overflow-y: auto;
  overflow-x: hidden;
  scroll-behavior: smooth; /* 添加平滑滚动 */
}

/* 当有消息时，改变对齐方式 */
.chat-container.has-messages {
  align-items: flex-start;
}

.chat-content {
  width: 100%;
  max-width: 800px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 40px;
  height: 100%;
  min-height: 100%; /* 确保有最小高度 */
}

/* 当有消息时，改变布局模式 */
.chat-content.has-messages {
  justify-content: flex-start;
  height: fit-content; /* 使用 fit-content 让内容决定高度 */
  min-height: 100%; /* 保持最小高度为容器高度 */
  gap: 0;
  padding: 20px 20px 140px 20px; /* 调整底部padding，为输入框和footer留空间 */
  position: relative;
}

.welcome-message {
  text-align: center;
  flex-shrink: 0;
}

.welcome-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
  line-height: 1.2;
}

.welcome-subtitle {
  font-size: 16px;
  color: #666;
  line-height: 1.5;
  margin: 0;
}

/* 欢迎页面的输入框容器 */
.input-wrapper {
  width: 100%;
  flex-shrink: 0;
  position: relative;
  background: #fff;
  border: 1px solid #e5e5e6;
  border-radius: 12px;
  padding: 12px 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-width: 800px;
  margin: 0 auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

/* 对话模式下固定在底部的输入框 */
.input-container-fixed {
  position: fixed;
  bottom: 36px; /* 调整为全局footer的高度，确保无缝隙 */
  left: 300px;
  right: 30px;
  z-index: 100;
  background: #fff;
}

.input-wrapper:focus-within {
  border-color: #1a73e8;
  box-shadow: 0 2px 8px rgba(26, 115, 232, 0.2);
}

.input-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
  flex-shrink: 0;
}

.attach-btn {
  background: transparent;
  border: none;
  color: #666;
  width: 32px !important;
  height: 32px !important;
  transition: all 0.2s;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.attach-btn:hover {
  background: #f0f7ff;
  color: #1a73e8;
}

.send-btn {
  width: 32px !important;
  height: 32px !important;
  background: #1a73e8;
  border: none;
  transition: all 0.2s;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:hover {
  background: #0d5fd1;
}

.send-btn:disabled {
  background: #e0e0e0;
  color: #a8a8a8;
  cursor: not-allowed;
}

.ai-name {
  color: #1a73e8;
  font-weight: 600;
}

/* 全局底部提示样式 */
.global-footer {
  position: fixed;
  bottom: 0;
  left: 300px;
  right: 30px;
  background: #fff;
  padding: 8px 16px;
  text-align: center;
  z-index: 99;
}

.global-hint {
  font-size: 12px;
  color: #666;
  font-weight: 400;
}

.chat-history {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  padding: 0 20px;
  flex: 1; /* 让聊天历史占据可用空间 */
  overflow-y: visible; /* 确保内容可见 */
}

.msg-row {
  display: flex;
  padding: 16px 0;
}

.msg-row.assistant {
  justify-content: flex-start;
}

.msg-row.user {
  justify-content: flex-end;
}

.msg-avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  margin-right: 16px;
}

.msg-row.user .msg-avatar {
  order: 1;
  margin-right: 0;
  margin-left: 16px;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.msg-content-wrapper {
  max-width: calc(100% - 80px);
  min-width: 0;
}

.msg-content {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  word-break: break-word;
  white-space: pre-wrap;
  padding: 12px 16px;
  border-radius: 12px;
  max-width: 100%;
  width: fit-content;
}

.msg-content pre {
  margin: 0;
  white-space: pre-wrap;
  font-family: inherit;
}

.msg-content.assistant {
  background-color: #f5f5f5;
  border-top-left-radius: 0;
}

.msg-content.user {
  background-color: #e6f2ff;
  border-top-right-radius: 0;
}

.message-container-wrapper {
  width: 100%;
  max-width: 800px;
  background: #fff;
  padding: 0 20px 20px 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 在欢迎模式下确保输入框能正确定位 */
  margin-top: auto;
}

.message-container {
  width: 100%;
  max-width: 800px;
  box-sizing: border-box;
}

.input-container {
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  gap: 8px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 12px 16px;
  border: 1px solid #e5e5e6;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.action-buttons-row {
  display: flex;
  justify-content: flex-end;
}

.input-container:focus-within {
  border-color: #1a73e8;
  box-shadow: 0 2px 8px rgba(26, 115, 232, 0.2);
}

.message-input {
  flex: 1;
  border: none;
  box-shadow: none;
  padding: 8px 0;
}

.message-input:deep(.el-textarea__inner) {
  box-shadow: none !important;
  border: none !important;
  padding: 0 !important;
  resize: none;
  max-height: 120px;
  font-size: 16px;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 8px;
  margin-bottom: 0;
}

.attach-btn {
  border: none;
  color: #666;
  background-color: transparent;
  transition: all 0.2s;
}

.attach-btn:hover {
  color: #1a73e8;
  background-color: #f0f7ff;
}

.send-btn {
  background-color: #1a73e8;
  color: white;
  border: none;
  transition: all 0.2s;
}

.send-btn:hover {
  background-color: #0d5fd1;
}

.send-btn:disabled {
  background-color: #e0e0e0;
  color: #a8a8a8;
  cursor: not-allowed;
}

.attach-btn:deep(.el-icon),
.send-btn:deep(.el-icon) {
  font-size: 20px !important;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.disclaimer-bottom {
  text-align: center;
  font-size: 12px;
  color: #999;
  margin-top: 12px;
}

/* Loading 动画样式 */
.loading-content {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.loading-dots {
  display: flex;
  gap: 4px;
}

.loading-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #1a73e8;
  animation: loading-bounce 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

.loading-text {
  font-size: 14px;
  color: #666;
}

.loading-history {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
}

@keyframes loading-bounce {
  0%,
  80%,
  100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

/* Element Plus 输入框自定义样式 */
:deep(.el-textarea__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  resize: none;
  padding: 8px 0;
  font-size: 16px;
  line-height: 1.5;
  min-height: 24px;
  max-height: 200px;
}

:deep(.el-textarea__inner:focus) {
  box-shadow: none !important;
  border: none !important;
}

:deep(.el-textarea) {
  --el-input-focus-border-color: transparent;
  --el-textarea-padding-horizontal: 0;
  --el-textarea-padding-vertical: 0;
}

:deep(.el-input__wrapper) {
  box-shadow: none !important;
  padding: 0 !important;
  border: none !important;
  background: transparent !important;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: none !important;
  border: none !important;
}

/* Button 圆形样式优化 */
:deep(.el-button.is-circle) {
  padding: 0 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  border: none !important;
  min-width: auto !important;
  width: 32px !important;
  height: 32px !important;
}

:deep(.el-button.is-circle .el-icon) {
  font-size: 16px !important;
  width: 16px !important;
  height: 16px !important;
  line-height: 1 !important;
}

/* Tooltip 自定义样式 */
:deep(.el-tooltip__content) {
  max-width: 400px;
  white-space: nowrap;
  line-height: 1.4;
  padding: 8px 12px;
  font-size: 12px;
  background-color: rgba(0, 0, 0, 0.8);
  border-radius: 6px;
}
</style>
